/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.Post;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Owner
 */
@Stateless
public class PostManagerBean implements PostManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Post post)throws Exception {
        em.persist(post);
    }
 
    public void update(Post post)throws Exception {
        em.merge(post);
    }
    
    public void delete(Post post)throws Exception {
        post=em.merge(post);
        em.remove(post);
    }
    
    public Post find(long id){
        return em.find(Post.class,id);
    }

    public List<Post> listAll(){
        Query query=em.createNamedQuery("listAllPosts");
        List<Post> result=query.getResultList();
        return result;
    }
    
    public List<Post> postingsUser(RegisterUser registerUser){
        Query query=em.createNamedQuery("postingsUser");
        query.setParameter("registerUser", registerUser);
        List<Post> result=query.getResultList();
        return result;
    }
    
    public List<Post> getPostsFound(String st, String ft){
        Query query=em.createQuery("SELECT p " +
                "                   FROM Post p " +
                "                   WHERE p.type=:st AND p." + ft+">0"+
                "                   ORDER BY p." + ft);
        query.setParameter("st", st);
        
        List<Post> result=query.getResultList();
        return result;
    }
    
    public Post getPostingFound(Site site, String type, long id){
        try{
            Query query=em.createNamedQuery("postingFound");
            query.setParameter("site", site);
            query.setParameter("type", type);
            query.setParameter("id", id);
            Post result=(Post) query.getSingleResult();
            return result;
        } catch (Exception ex) {
            return null;
        }
    }
    
}
